package com.study.modules.saas.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.study.common.BusinessException;
import com.study.Util.IDUtil;
import com.study.modules.saas.repository.dao.ImageDao;
import com.study.modules.saas.repository.model.ImageDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author hupengming
 * @ClassName
 * @Date 2022-10-28 14:28
 * @Version 1.0
 */
@Slf4j
@Service
public class ImageService {

    @Autowired
    ImageDao imageDao;

    @Autowired
    CosService cosService;

    private static final String IMAGE_PATTERN = "([^\\s]+(\\.(?i)(jpg|jpeg|png|JPG|JPEG|PNG))$)";

    private void validate(final String image) {
        Matcher matcher = Pattern.compile(IMAGE_PATTERN).matcher(image);
        boolean matches = matcher.matches();
        if (!matches) {
            throw new BusinessException("请传正确的图片类型 .jpg .jpeg .png");
        }
    }

    /**
     * 添加图片
     *
     * @param file
     * @return
     */
    public int addImage(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        this.validate(fileName);
        String key = String.format("%s%s", IDUtil.randomUUID(), fileName);
        log.info("key:{}", key);
        String imagePath = cosService.load(key, file);
        ImageDO imageDO = new ImageDO();
        imageDO.setImagePath(imagePath);
        imageDO.setKey(key);
        imageDO.setStatus(Boolean.TRUE);
        imageDO.setCreatedAt(new Date());
        int re = imageDao.insert(imageDO);
        if(re == 0){
            cosService.delete(key);
        }
        return re;
    }

    public void deleteImage(String key){
        if(StringUtils.isNotEmpty(key)){
            ImageDO imageDO = imageDao.selectOne(new LambdaQueryWrapper<ImageDO>().eq(ImageDO::getKey, key));
            if(Objects.nonNull(imageDO)){
                cosService.delete(key);
                imageDao.delete(new LambdaQueryWrapper<ImageDO>().eq(ImageDO::getKey,key));
            }
        }
    }

    public ImageDO getImage(String path){
        return imageDao.selectOne(new LambdaQueryWrapper<ImageDO>().eq(ImageDO::getImagePath,path));
    }

    public void updateImage(ImageDO imageDO){
        imageDao.updateById(imageDO);
    }


}
